#include "../process.h"
#include "../util.h"

double increase_ratio(int gd, int qd)
{
	return (double)(gd - qd)/qd;
}

bool comp (const pair<int, double> &p1, const pair<int, double> &p2)
{
	if(p1.first == p2.first)
		return p1.second > p2.second;
	else
		return p1.first > p2.first;
}


int main(int argc, const char* argv[])
{
	fstream input(argv[1], fstream::in);
	fstream output(argv[2], fstream::out);
	vector<pair<int, double>> data_points;
	string line;
	while(!input.eof())
	{
		getline(input, line);
		if (line.length() == 0)continue;
		int del1 = line.find('\t'), 
			del2 = line.find('\t', del1 + 1), 
			del3 = line.find('\t', del2 + 1);
		string gid = line.substr(0, del1), elements_s = line.substr(del3 + 1, line.length() - del3 - 1);
		int	gd = atoi(line.substr(del1 + 1, del2 - del1 - 1).c_str());
			
		vector<string> elements = util::tokenize_h(elements_s, " | ");
		for(int i = 0; i < elements.size(); ++ i)
		{
			string qfd = elements[i];
			del1 = qfd.find('\t');
			del2 = qfd.find('\t', del1 + 1);
			int qd = atoi(qfd.substr(del1 + 1, del2 - del1 - 1).c_str());
			int qf = atoi(qfd.substr(del2 + 1, qfd.length() - del2 - 1).c_str());
			data_points.push_back(pair<int, double>(qf, increase_ratio(gd, qd)));
		}		
	}
	sort(data_points.begin(), data_points.end(), comp);
	for(int i = 0; i < data_points.size(); ++ i)
		output << data_points[i].first << "\t" << data_points[i].second << endl;
	return 0;
}